package v1

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"teacher-helper/middleware"
	"teacher-helper/service"
)

// @用户登录
// @Description Login
// @Accept  application/x-www-form-urlencoded
// @Summary 用户登录
// @Produce  application/x-www-form-urlencoded
// @param username formData string true "用户名"
// @param password formData string true "密码"
// @Success 200 {string} string "{"token": "","data":user,"msg":"登陆成功"}"
// @failure 201 {string} string "{"data":user,"msg":"参数获取错误"}"
// @Router /api/v1/login [post]
func Login(c *gin.Context){
	username, nameOK := c.GetPostForm("username")
	password, pwdOK := c.GetPostForm("password")
	if !nameOK || !pwdOK{
		c.JSON(201, gin.H{"msg": "参数接收错误", "data": nil})
		return
	}
	user, msg, isPass := service.LoginCheck(username, password)
	if !isPass {
		c.JSON(202, gin.H{
			"msg":msg,
			"data":nil,
		})
	}else {
		token, msg, ok := middleware.GenerateToken(c, user)
		if !ok {
			c.JSON(203, gin.H{"msg": msg, "data": nil})
		}else {
			c.JSON(http.StatusOK, gin.H{"msg":msg, "token": token, "data": user})
		}
	}
	return
}

